package com.huilian.iotbox.data.utils;

import com.alibaba.fastjson.JSONObject;
import com.huilian.iotbox.data.dto.WeiXinDto;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;

/**
 * @Author: yjzhang
 * @Date: 2020/5/23 11:58
 */
public class WxAESUtil {

    public static JSONObject getWxUserInfo(WeiXinDto weiXinDto) throws Exception {
        // 获取参数
        String strCipher = "";
        String strEncrypdata = weiXinDto.getEncryptedData();
        String strIvdata = weiXinDto.getIv();
        String strSessionkey= weiXinDto.getSessionKey();

        byte[] byEncrypdata = Base64.decodeBase64(strEncrypdata);
        byte[] byIvdata = Base64.decodeBase64(strIvdata);
        byte[] bySessionkey = Base64.decodeBase64(strSessionkey);


        JSONObject jsData = new JSONObject();

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(byIvdata);
        Cipher cipher;
        SecretKeySpec keySpec = new SecretKeySpec(bySessionkey, "AES");
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            strCipher = new String(cipher.doFinal(byEncrypdata),"UTF-8");
            jsData.put("phone", strCipher);

        } catch (Exception e) {
            Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            cipher2.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            strCipher = new String(cipher2.doFinal(byEncrypdata), "UTF-8");
            jsData.put("phone", strCipher);
        }

        return jsData;
    }


}
